<?php
/**
 * Created by PhpStorm.
 * User: gby
 * Date: 2018/8/31
 * Time: 11:22
 */
namespace Services;

use Helpers\HttpClient;
use Helpers\Tool;
use Helpers\Main;
use Helpers\XhException;

class MicroServer
{
    /**
     * @var \Helpers\HttpClient
     */
    public static $httpClient;
    public static $url;
    public static $microEnum = [
        'status'    => [
            true => '<div class="grid-cell-text-bg-green">正常</div>',
            false => '<div class="grid-cell-text-bg-red">下线</div>'
        ],
        'source'    =>[
             0 => '后台注册',
             1 => '盒子注册',
        ],
        'enabled'   => [
            true => '<div class="grid-cell-text-bg-green">正常</div>',
            false => '<div class="grid-cell-text-bg-red">下线</div>'
        ],
        'type'      => [
             'SERVER' => '服务',
             'SCHOOL' => '学校',
        ],
        'tactic'    => [
            'AUTO' => '自动',
            'DEFAULT' => '默认',
            'ORDER' => '优先级',
            'ALLOT' => '指定',
            'HASH' => '哈希',
            'WEIGHT' => '权重',
            'CUSTOM' => '自定义',
            'SPECIAL' => '域名IP优先排序',
        ],
        'customType'=> [
            'IP' => 'IP',
            'DOMAIN' => '域名',
            'SERVER' => '服务',
            'EXCLUDE' => '排除',
        ]
    ];

    /**
     * 初始化配置
     *
     * @throws XhException
     *
     * create by gby 20180831
     */
    public static function init()
    {
        if (!self::$httpClient) {
            $config = Main::getConfigByName('microServer');
            self::$url  = Tool::getValue($config, 'url');
            if (!self::$url) {
                throw new XhException('微服务url获取失败');
            }
            self::$httpClient = new HttpClient(self::$url);
        }
    }

    /**
     * 获取微服务列表数据
     *
     * @param int $page
     * @param int $size
     * @param array $search
     * @return array
     *
     * @throws XhException create by gby 20180831
     */
    public static function getData($page = 1, $size = 25, $search = [])
    {
        self::init();
        $response = self::$httpClient->get(
            'api/v2/pri/microServer/search/',
            array_merge([
            'page' => $page - 1,
             'size' => $size
            ], $search)
        );
        if (!$response->isSuccess()) {
            throw new XhException('获取微服务列表失败', $response);
        }
        $body = $response->toArray();
        $data = [
            'total' => $body['totalElements'],
            'rows'  => $body['content']
        ];
        Tool::runEnum($data['rows'], self::$microEnum);
        Tool::runTimestamp($data['rows'], 'updateTime');
        return $data;
    }

    /**
     * 注册服务/更新服务
     *
     * @param $params
     * @return bool
     * @throws XhException
     *
     * create by gby 20180831
     * modify by fyh 20181109
     */
    public static function register($params = [])
    {
        self::init();
        $response = self::$httpClient->postJson('api/v3/pri/microServer', $params);
        if (!$response->isSuccess()) {
            throw new XhException('操作失败', $response);
        }
        return true;
    }

    /**
     * 更新服务
     *
     * @param $serverId
     * @param $params
     * @throws XhException
     * @return bool
     *
     * create by gby 20180831
     * modify by fyh 20181112
     */
//    public static function update($serverId, $params)
//    {
//        self::init();
//        $response = self::$httpClient->putJson(sprintf('api/v2/pri/microServer/%s', $serverId), $params);
//        if (!$response->isSuccess()) {
//            throw new XhException('操作失败', $response);
//        }
//        return true;
//    }

    /**
     * 停用服务
     *
     * @param $desc
     * @param $serverIds
     * @return bool
     * @throws XhException
     *
     * create by gby 20180831
     */
    public static function stop($serverIds, $desc = '')
    {
        self::init();
        $params['desc'] = $desc;
        $params['serverIds'] = $serverIds;
        $response   = self::$httpClient->patchJson('api/v1/pub/microServer/stop', $params);
        if (!$response->isSuccess()) {
            throw new XhException('操作失败', $response);
        }
        return true;
    }

    /**
     * 启用服务
     *
     * @param $desc
     * @param $serverIds
     * @throws XhException
     * @return bool
     * create by gby 20180831
     */
    public static function start($serverIds, $desc = '')
    {
        self::init();
        $params['desc'] = $desc;
        $params['serverIds'] = $serverIds;
        $response   = self::$httpClient->patchJson('api/v1/pub/microServer/start', $params);
        if (!$response->isSuccess()) {
            throw new XhException('操作失败', $response);
        }
        return true;
    }

    /**
     * 删除服务
     *
     * @param $desc
     * @param $serverIds
     * @throws XhException
     * @return bool
     *
     * create by gby 20180831
     * modify by fyh 20181113
     */
    public static function delete($serverIds, $desc = '')
    {
        self::init();
        $params['desc'] = $desc;
        $params['serverIds'] = $serverIds;
        $response = self::$httpClient->setBodyParams($params, true)->delete('api/v1/pub/microServer/', $params);
        if (!$response->isSuccess()) {
            throw new XhException('操作失败', $response);
        }
        return true;
    }

    /**
     * 获取微服务配置列表数据
     *
     * @param int $page
     * @param int $size
     * @param array $search
     * @param $serverType
     * @return array
     * @throws XhException
     *
     * create by fyh 20181129
     */
    public static function getConfigData($page = 1, $size = 25, $search = [], $serverType = 'SCHOOL')
    {
        self::init();
        $response = self::$httpClient->get(
            'api/v1/pri/tactic/config',
            array_merge([
             'page' => $page - 1,
             'size' => $size,
             'type' =>$serverType
            ], $search)
        );
        if (!$response->isSuccess()) {
            throw  new XhException('获取微服务配置失败', $response);
        }
        $body = $response->toArray();
        $data = [
            'total' => $body['totalElements'],
            'rows'  => $body['content']
        ];
        Tool::runEnum($data['rows'], self::$microEnum);
        Tool::runTimestamp($data['rows'], 'updateDate');
        return $data;
    }

    /**
     * 获取一条微服务配置数据
     *
     * @param $id
     * @param $type
     * @return bool
     * @throws XhException
     *
     * create by fyh 20181129
     */
    public static function getConfigOne($id, $type)
    {
        self::init();
        if ($type == 'ACCESS') {
            $url = 'api/v1/pri/tactic/access/config/%s';
        } elseif ($type == 'APP') {
            $url = 'api/v1/pri/tactic/app/config/%s';
        } else {
            $url = 'api/v1/pri/tactic/school/config/%s';
        }
        $response = self::$httpClient->get(
            sprintf($url, $id)
        );
        if (!$response->isSuccess()) {
            throw new XhException('操作失败', $response);
        }
        $body = $response->toArray();
        return $body;
    }


    /**
     * 注册服务配置
     *
     * @param $params
     * @return bool
     * @throws XhException
     *
     * create by fyh 20181129
     */
    public static function registerConfig($params = [])
    {
        self::init();
        if ($params['type'] == 'SCHOOL') {
            $url = "api/v1/pri/tactic/school/app/config";
        } elseif ($params['type'] == 'APP') {
            $url = "api/v1/pri/tactic/app/config";
        } else {
            $url = "api/v1/pri/tactic/access/app/config";
        }
        $response = self::$httpClient->postJson($url, $params);
        if (!$response->isSuccess()) {
            throw new XhException('操作失败1', $params);
        }
        return true;
    }

    /**
     * 更新服务配置
     *
     * @param $serverId
     * @param $params
     * @throws XhException
     * @return bool
     *
     * create by fyh 20181129
     */
    public static function updateConfig($serverId, $params)
    {
        self::init();
        if ($params['type'] == 'SCHOOL') {
            $url = 'api/v1/pri/tactic/school/config/%s';
            $data['customConfigRequests'] = $params['customConfigRequests'];
        } elseif ($params['type'] == 'APP') {
            $url = 'api/v1/pri/tactic/app/config/%s';
            $data['tactic'] = $params['tactic'];
        } else {
            $url = 'api/v1/pri/tactic/school/config/%s';
            $data['addressReturnType'] = $params['addressReturnType'];
        }
        $response = self::$httpClient->putJson(sprintf($url, $serverId), $data);
        if (!$response->isSuccess()) {
            throw new XhException('操作失败', $response);
        }
//        throw new XhException('操作成功', $response);
        return true;
    }

    /**
     * 删除服务配置
     *
     * @param $serverIds
     * @throws XhException
     * @return bool
     *
     * create by fyh 20181129
     */
    public static function deleteConfig($serverIds)
    {
        self::init();
        $params['configId'] = $serverIds;
        $response = self::$httpClient->delete(sprintf('api/v1/pri/tactic/config/%s', $serverIds));
        if (!$response->isSuccess()) {
            throw new XhException('操作失败', $response);
        }
        return true;
    }
}